package com.chinasoft.maysham.manager.util;

import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@Component
public class HttpClient {
    @Resource
    private RestTemplate restTemplate;

    public String get(String url, Map<String, ?> uriParam) {
        ResponseEntity<String> entity = restTemplate.exchange(url, HttpMethod.GET, null, String.class, uriParam);
        return entity.getBody();
    }

    public void getForFile(String url, Map<String, ?> uriParam, OutputStream outputStream) {
        restTemplate.execute(url, HttpMethod.GET, clientHttpRequest -> {

        }, res -> {
            InputStream in = res.getBody();
            byte[] temp = new byte[1024];
            int i = -1;
            while ((i = in.read(temp)) > -1) {
                outputStream.write(temp, 0, i);
            }
            outputStream.flush();
            return "";
        }, uriParam);
    }
}
